<?php

// +----------------------------------------------------------------------
// | EasyAdmin
// +----------------------------------------------------------------------
// | PHP交流群: 763822524
// +----------------------------------------------------------------------
// | 开源协议  https://mit-license.org
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zhongshaofa/EasyAdmin
// +----------------------------------------------------------------------

namespace app\admin\model\shop;

use app\common\model\TimeModel;

class Goods extends TimeModel
{
    protected $name = 'goods';
    protected $pk = 'products_id';
    
    public function cate()
    {
        return $this->belongsTo(Category::class,'cate_id','cate_id');
    }

    public function setSpecsAttr($value)
    {
        if($value){
            if(is_array($value)) return implode(',', $value); else return $value;
        }else{
            return "";
        }
        
    }

    public function setSkusAttr($value)
    {
        return json_encode($value);
    }

    public function setSpecsValueAttr($value)
    {

        return json_encode($value);
    }
    public static function onAfterInsert($data)
    {   
       
        $data=$data->toArray();
        
    	if(!empty($data['product_value'])){
            foreach ($data['product_value'] as $k => $v) {
            
                $data['product_value'][$k]['products_id']=$data['products_id'];
                
            }
            $SpecItem=new GoodsValue();
            $SpecItem->saveAll($data['product_value']);
        }
        
    }

    public static function onAfterUpdate($data)
    {   
       
        $data=$data->toArray();
        
    	if(!empty($data['product_value'])){
            foreach ($data['product_value'] as $k => $v) {
                $data['product_value'][$k]['products_id']=$data['products_id'];
            }
            $SpecItem=new GoodsValue();
            $SpecItem->where('products_id',$data['products_id'])->delete();
            $SpecItem->saveAll($data['product_value']);
        }
        
    }
   
}
